#include "languageframe.h"
#include <QHBoxLayout>
#include <QMenu>
#include <QProcess>
#include <QDebug>
#include <QTextCodec>
#include "common.h"

LanguageFrame::LanguageFrame(QString showName, QWidget *parent)
    :UkccFrame(parent, BorderRadiusStyle::Top, true)
{
    QHBoxLayout *layout = new QHBoxLayout(this);
    layout->setContentsMargins(16, 0, 16, 0);

    nameLabel = new QLabel();
    nameLabel->setText(showName);

    selectedIconLabel = new QLabel();
    QFrame *frame = new QFrame(this);
    frame->setFixedSize(16, 16);
    QHBoxLayout *frameLayout = new QHBoxLayout(this);
    frameLayout->setMargin(0);
    frame->setLayout(frameLayout);
    selectIcon = QIcon::fromTheme("ukui-selected");
    selectedIconLabel->setPixmap(selectIcon.pixmap(selectIcon.actualSize(QSize(16, 16))));
    selectedIconLabel->setVisible(false);

    layout->addWidget(nameLabel);
    layout->addStretch();
    layout->addWidget(createToolBtn());
    frameLayout->addWidget(selectedIconLabel);
    layout->addWidget(frame);
    this->setObjectName("LanguageFrame");
}

LanguageFrame::~LanguageFrame()
{

}

void LanguageFrame::mousePressEvent(QMouseEvent *e)
{
    if (!isSelection()) {
        this->showSelectedIcon(true);
        Q_EMIT clicked();
    }
    return;
}

void LanguageFrame::showSelectedIcon(bool flag)
{
    selectedIconLabel->setVisible(flag);
}

bool LanguageFrame::isSelection()
{
    return selectedIconLabel->isVisible();
}

QToolButton* LanguageFrame::createToolBtn()
{
    QToolButton *btn = new QToolButton(this);
    btn->setAutoRaise(true);
    btn->setPopupMode(QToolButton::InstantPopup);
    QMenu *menu = new QMenu(btn);
    btn->setMenu(menu);
    QAction *edit = new QAction(btn);
    QAction *del = new QAction(btn);
    edit->setText(tr("Input Settings"));
    del->setText(tr("Delete"));
    menu->addAction(edit);
    menu->addAction(del);

    connect(menu, &QMenu::aboutToShow, [=](){
        if (selectedIconLabel->isVisible()) {
            del->setEnabled(false);
        } else {
            del->setEnabled(true);
        }
    });

    connect(del, &QAction::triggered, this, [=](){
        Q_EMIT deleted();
        this->deleteLater();
    });

    connect(edit, &QAction::triggered, this, [=](){
        QProcess process;
        process.startDetached("fcitx5-config-qt");

    });

    btn->setIcon(QIcon::fromTheme("view-more-horizontal-symbolic"));
    btn->setProperty("useButtonPalette", true);
    return btn;
}

QString LanguageFrame::getShowName()
{
    return this->nameLabel->text();
}

void LanguageFrame::reloadIcon()
{
     selectedIconLabel->setPixmap(selectIcon.pixmap(selectIcon.actualSize(QSize(16, 16))));
}
